package com.zizo.util;

import java.net.SocketTimeoutException;

import org.jsoup.HttpStatusException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

/**
 * @ClassName: DocUtil
 * @Description: TODO Jsoup获得 Document文档的一个封装类，原始的getDoc(String url)方法不允许重写，可以重载
 * @author: Alexis
 * @date: 2016年7月22日 下午12:49:00
 */
public class DocUtil {

	public static Document getDoc(String url) {
		Document doc = null;
		int i = 0;
		while (i < 5) {
			try {
				doc = Jsoup.connect(url)
						.userAgent(
								"Mozilla/5.0 (Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36")
						.followRedirects(true).timeout(10000).get();
				break;
			} catch (SocketTimeoutException se) {
				System.out.println("Read Time Out " + Util.getCurrentDateTime() + " :" + url);
			} catch (HttpStatusException hse) {
				// bbs http 403 错误
			} catch (Exception e) {
				System.out.println(url);
				e.printStackTrace();
			}
			i++;
		}
		return doc;
	}

	public static Document getDocByProxy(String url) {
		Document doc = null;
		int i = 0;
		while (i < 5) {
			try {
				doc = Jsoup.connect(url)
						.userAgent(
								"Mozilla/5.0 (Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36")
						.followRedirects(true).timeout(10000).proxy("124.240.187.78", 81).get();
				break;
			} catch (SocketTimeoutException se) {
				System.out.println("Read Time Out " + Util.getCurrentDateTime() + " :" + url);
			} catch (HttpStatusException hse) {
				// bbs http 403 错误
			} catch (Exception e) {
				e.printStackTrace();
			}
			i++;
		}
		return doc;
	}

	/**
	 * @Title: getDocByFile
	 * @Description: TODO 通过Filename获取Document对象
	 * @param pathname
	 * @return
	 * @return Document
	 * @author Alexis
	 */
	public static Document getDocByFile(String pathname) {
		Document doc = null;
		try {
			String body = Gzip.decompress(pathname);
			doc = Jsoup.parse(body);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return doc;
	}

	/**
	 * 
	 * 获得json格式页面数据，返回字符串格式，根据返回的格式要对返回数据处理
	 * 
	 * 
	 * 
	 * @param url
	 *            请求地址
	 * 
	 * @return string 返回字符串
	 * 
	 */
	public static String getJsonDataFromUrl(String url) {
		String body = null;
		int i = 0;
		while (i < 5) {
			try {
				body = Jsoup.connect(url).timeout(30000).ignoreContentType(true).execute().body();
				break;
			} catch (Exception e) {
				i++;
			}
		}
		return body;
	}
}
